package ge.telasi.tasks.controller;

import ge.telasi.tasks.EJBLocaleManager;
import ge.telasi.tasks.LocaleManager;
import ge.telasi.tasks.TaskException;
import ge.telasi.tasks.model.User;
import javax.persistence.EntityManager;

public abstract class Controller {

    LocaleManager getLocaleManager() {
        return new EJBLocaleManager();
    }

    void requireAdmin(EntityManager em, User user) {
        UserController controller = new UserController();
        int userCount = controller.getActiveUserCount(em);
        // check for admin privilegies only when there
        // are at least one active user in database
        if (userCount > 0) {
            if (user == null) {
                String msg = getLocaleManager().getMessage("Controller.requireAdmin");
                throw new TaskException(msg, "User.userNotAuthorized");
            }
            user = controller.find(em, user.getUsername());
            if (!user.isAdmin()) {
                String msg = getLocaleManager().getMessage("Controller.requireAdmin");
                throw new TaskException(msg, "User");
            }
        }
    }

}
